<template>
  <div class="main-content">

    <IsLoading v-if="isLoading"></IsLoading>

    <!--左边区域-->
    <div class="scalable-container" :style="{ transform: `scale(${scale})`, transformOrigin: 'top' }">
      <!-- 页面内容 -->
      <div class="content">

        <div>
          <el-row>
            <el-col :span=" 3 " class="item-left">
              <!--          导航栏区域-->
              <div>
                <div style="font-size: 20px;font-weight: bold;text-align: center;margin: 20px 0">
                  助教下载站
                </div>
                <div style="margin-top: 20px; position: relative;">
                  <el-button icon="el-icon-menu" class="left-scroll-view-item"
                             :class="{'is-active': activeIndex === null}"
                             @click="setActive(null)"
                             style="flex: 1; width: 100%; box-sizing: border-box;height: 50px; position: relative; overflow: hidden;">
                    全部分类
                    <div v-if="activeIndex === null" class="active-indicator"></div>
                  </el-button>

                  <el-scrollbar wrap-style="overflow-x:hidden;" style="height: 500px;">
                    <el-button v-for="(item, index) in buttonItems" :key="index" type="text"
                               class="left-scroll-view-item"
                               :class="{'is-active': activeIndex === index}" @click="setActive(index, item.id)"
                               style="flex: 1; width: 100%; box-sizing: border-box;height: 50px; position: relative; overflow: hidden;padding-right: 3px">
                      <img :src="IMAGE_URL + item.img" style="width: 21px;height: 15px;padding-right: 8px;">
                      {{ item.name }}
                      <div v-if="activeIndex === index" class="indicator-line"></div>
                    </el-button>
                  </el-scrollbar>
                </div>

                <!--          下方图片区域 -->
                <div class="image-button-container">
                  <img src="@/assets/imgs/homeTwo.png"
                       style="width: 100%; height: auto; display: block;margin-top: 60px">
                  <!--                  <el-button v-if="!isApp" size="mini" class="positioned-button">Xia Zai Zhan</el-button>-->
                </div>
              </div>
            </el-col>

            <!--        右边区域-->
            <el-col :span=" 20 " class="item-right">

              <!--              <div class="input-with-button" style="box-shadow: 6px 6px 6px 6px rgba(0, 0, 0, 0.1);padding: 3px 10px">-->
              <!--              输入框区域-->
              <!--                <el-input prefix-icon="el-icon-search" v-model="activeIndex" placeholder="搜索您所需要的文件"-->
              <!--                          style="margin: 20px 10px; width:70%;margin-right: 23px" clearable></el-input>-->
              <!--                &lt;!&ndash;              问号区域&ndash;&gt;-->
              <!--                &lt;!&ndash;              <el-button type="primary" size="small" circle icon="el-icon-question"&ndash;&gt;-->
              <!--                &lt;!&ndash;                         style="margin-left: -12px; /* 根据需要调整 */"></el-button>&ndash;&gt;-->
              <!--                <el-link icon="el-icon-question" style="font-size: 23px;color: #d4dff4"></el-link>-->
              <!--              </div>-->

              <div class="breadcrumb-and-rank" style="">
                <el-breadcrumb separator-class="el-icon-arrow-right" style="flex:1">
                  <el-breadcrumb-item :to="{ path: '/front/homeFront' }">首页</el-breadcrumb-item>
                  <el-breadcrumb-item v-if="isActiveSet" style="cursor: pointer"
                                      :to="{ path: '/front/drive', query: { apps:this.apps, pid:this.pid, categoryName: this.form.categoryName, activeIndex:this.activeIndex }}">
                    {{ form.categoryName }}
                  </el-breadcrumb-item>
                  <el-breadcrumb-item v-else style="cursor: pointer"
                                      :to="{ path: '/front/drive', query: { apps:this.apps, pid:this.form.pid, categoryName: this.form.categoryName, activeIndex:this.activeIndex }}">
                    {{ form.categoryName }}
                  </el-breadcrumb-item>
                  <el-breadcrumb-item v-if="currentSearchValue !== null">{{ currentSearchValue }}</el-breadcrumb-item>
                  <!-- 使用 categoryName -->
                </el-breadcrumb>
                <!--                <span class="rank-text" style="margin-left: auto;">排行榜</span>-->
              </div>

              <!--            热门推荐区域-->
              <!--              <div class="hot" v-if="!isApp">-->
              <!--                <el-row>-->
              <!--                  <div style="font-size: 17px;font-weight: bold;margin: 13px 0">热门推荐</div>-->
              <!--                  <el-col :span="6" v-for="(item, index) in hots" :key="index">-->
              <!--                    <div class="card" style="display: flex;flex-direction: row;margin: 10px;padding: 20px;box-shadow: 6px 6px 6px rgba(0,0,0,0.1);background-color: #f0f0f0;-->
              <!--                    border-radius: 8px;text-align: center;box-sizing: border-box;align-items: center;">-->
              <!--                      <img :src="item.img" style="width: 85px; height: 75px; margin-right: 20px;">-->
              <!--                      <div style="display: flex;flex: 1;flex-direction: column;justify-content: space-between;">-->
              <!--                        <div style="margin: 7px 0; font-weight: bold;">{{ item.name }}</div>-->
              <!--                        <div>{{ item.desc }}</div>-->
              <!--                      </div>-->
              <!--                    </div>-->
              <!--                  </el-col>-->
              <!--                </el-row>-->
              <!--              </div>-->

              <!--            应用软件区域-->
              <!--              <div class="app">-->
              <!--                <div style="font-size: 17px;font-weight: bold;margin: 10px 8px">-->
              <!--                  {{ form.categoryName }}-->
              <!--                </div>-->
              <!--                <el-scrollbar wrap-style="overflow-x:hidden;" :style="{height: isApp ? '300px' : '300px'}">-->
              <!--                  <el-col :span="isApp ? 8 : 3" v-for="(item, index) in apps" :key="index">-->
              <!--                    <div class="card1" @click="search(item.name)">-->
              <!--                      <img :src="IMAGE_URL + item.img" class="image">-->
              <!--                      <div class="item-name">{{ item.name }}</div>-->
              <!--                    </div>-->
              <!--                  </el-col>-->
              <!--                </el-scrollbar>-->
              <!--              </div>-->

              <div class="item-right-behind">
                <div style="margin-top: 18px;padding: 13px 5px 5px 5px">
                  <el-button class="button-name" @click="searchall"
                             :type="null === currentSearchValue ? 'primary' : 'default'" plain>全部
                  </el-button>
                  <el-button @click="search(item.name)"
                             :type="item.name === currentSearchValue ? 'primary' : 'default'"
                             plain v-for="(item,i) in apps" :key="i" class="button-name">{{ item.name }}
                  </el-button>
                </div>


                <!-- 搜索结果列表 -->
                <div v-if="number" v-for="(item, i) in searchLists" :key="i">
                  <div class="card" @click="toDetail(item.id)">
                    <img :src="IMAGE_URL + item.img" class="img">
                    <div style="display: flex;flex: 1;flex-direction: column;">
                      <!--        第一行区域-->
                      <div style="display: flex;flex: 1">
                        <div class="name">{{ item.name }}</div>
                        <!--                        <div class="slugName">（{{ item.slugName }}）</div>-->
                        <div class="time">发布时间：{{ item.createTime }}</div>
                        <!--                        <div v-if="!isApp" class="time">更新时间：-->
                        <!--                          <span v-if="item.updateTime">{{ item.updateTime }}</span>-->
                        <!--                          <span v-else>暂无</span>-->
                        <!--                        </div>-->
                      </div>
                      <!--      第二行区域-->
                      <div class="introduction-ellipsis">
                        介绍：<span v-if="item.introduction">{{ item.introduction }}</span>
                        <span v-else>暂无</span>
                      </div>
                      <div>
                        <!--                        描述：<span v-html="item.description"></span>-->
                      </div>
                    </div>
                    <el-button plain type="primary" class="download-button">立即下载</el-button>
                  </div>
                </div>

                <div v-if="!number" class="empty">
                  <img src="@/assets/imgs/noNumber.png" style="display: flex;align-items: center"/>
                </div>

              </div>

              <!-- 分页区域 -->
              <div class="pagination" style="display: flex; justify-content: flex-end; margin: 25px 0;">
                <el-pagination background @current-change="handleCurrentChange" :current-page.sync="pageNum"
                               :page-sizes="[5, 10, 20, 30, 40, 50, 100]"
                               @size-change="handleSizeChange" :page-size="pageSize"
                               layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
              </div>

            </el-col>
          </el-row>
        </div>

      </div>
    </div>
  </div>
</template>

<script>
import config from "../../../config";

export default {
  name: 'HomeClick',
  data() {
    return {
      IMAGE_URL: config.IMAGE_URL,
      form: {
        name: this.$route.query.name,
        pid: this.$route.query.pid,
        id: this.$route.query.id,
        pId: this.$route.query.pId,
        categoryName: this.$route.query.categoryName,
        activeIndex: this.$route.query.activeIndex,
      },
      pageNum: 1,   // 当前的页码
      pageSize: 10,  // 每页显示的个数
      total: 0,
      buttonItems: [],
      apps: [],
      // 用于跟踪当前激活的按钮索引
      activeIndex: null,
      scale: 1,  // 初始缩放比例为 1，即原始大小
      searchLists: [],
      id: '',
      pid: '',
      pId: '',
      currentSearchValue: '',
      isActiveSet: false,
      isLoading: true,
      number: true,
    }
  },
  mounted() {
    // 监听滚轮事件
    window.addEventListener('wheel', this.handleWheelEvent);
  },
  beforeDestroy() {
    // 移除事件监听
    window.removeEventListener('wheel', this.handleWheelEvent);
  },
  created() {
    this.isLoading = true;  // 开始加载
    Promise.all([
      this.load(),
      this.judge()
    ]).then(() => {
      this.isLoading = false;
    }).catch((error) => {
      console.error('Error loading data:', error);
      this.isLoading = false;
    });
  },
  // async created() {
  //   this.load()
  //
  //   this.judge()
  //
  //   // this.loadApps()
  //   // this.fetchData()
  //
  //   // this.getActiveIndex();
  //   // await this.getId()
  // },
  methods: {
    judge() {
      if (this.form.pId || this.form.id) {
        this.getActiveIndex();
        this.getId()
      } else {
        this.loadApps()
        this.fetchData()
      }
    },
    async getId() {
      this.number = true
      let pIdPromise = Promise.resolve();
      if (this.form.id) {
        pIdPromise = this.$request.get(`/apis/downCategories/${this.form.id}`, {
          params: {
            typeId: 3
          }
        }).then(res => {
          this.pId = res.data.pid;
          return this.pId;
        });

        return pIdPromise.then(pId => {
          return Promise.all([
            this.$request.get(`/apis/downCategories/list`, {params: {pid: pId, typeId: 3,type:2}}).then(res => {
              // let allApps = [];
              // res.data.forEach(category => {
              //   if (category.children && category.children.length > 0) {
              //     allApps = allApps.concat(category.children);
              //   }
              // });
              // this.apps = allApps;
              // this.setActive(this.activeIndex, pId);
              this.apps = res.data
            }),
            this.$request.get(`/apis/downResources/${this.pageNum}/${this.pageSize}`, {
              params: {
                rootId: pId,
                typeId: 3
              }
            }).then(res => {
              this.searchLists = res.data?.list;
              this.total = res.data?.total;
              this.setActive(this.activeIndex, pId);
              if (this.total === 0) {
                this.number = false
              }
            })
          ]);
        });
      } else if (this.form.pId) {
        return Promise.all([
          this.$request.get(`/apis/downCategories/list`, {params: {pid: this.form.pId, typeId: 3,type: 2}}).then(res => {
            // let allApps = [];
            // res.data.forEach(category => {
            //   if (category.children && category.children.length > 0) {
            //     allApps = allApps.concat(category.children);
            //   }
            // });
            // this.apps = allApps;
            // this.setActive(this.activeIndex, this.form.pId);
            this.apps = res.data
          }),
          this.$request.get(`/apis/downResources/${this.pageNum}/${this.pageSize}`, {
            params: {
              rootId: this.form.pId,
              typeId: 3
            }
          }).then(res => {
            this.searchLists = res.data?.list;
            this.total = res.data?.total;
            this.setActive(this.activeIndex, this.form.pId);
            if (this.total === 0) {
              this.number = false
            }
          })
        ]);
      }
      return Promise.resolve();
    },
    getActiveIndex() {
      if (this.form.activeIndex) {
        this.activeIndex = Number(this.form.activeIndex);
      }
    },
    remove() {
      const queryString = window.location.search;
      if (queryString && queryString.length > 1) { // 假设至少有一个查询参数
        // 清除查询字符串并重定向
        const baseUrl = window.location.origin + window.location.pathname;
        // window.location.href = baseUrl;
        this.$router.push({path: '/front/homeClick'})
      }
    },
    handleWheelEvent(event) {
      // 检查是否按下了Ctrl键
      if (event.ctrlKey) {
        // 防止页面的默认缩放行为
        //event.preventDefault();

        // 判断滚轮方向
        if (event.deltaY < 0) {
          // 滚轮向上滚动，放大页面
          this.scale = Math.min(this.scale + 0.1, 2);  // 最大放大到2倍
        } else {
          // 滚轮向下滚动，缩小页面
          this.scale = Math.max(this.scale - 0.1, 0.5);  // 最小缩小到0.5倍
        }
      }
    },
    search(name) {
      this.number = true
      this.isLoading = true
      this.currentSearchValue = name; // 保存当前搜索值
      // 这里应该使用组件的初始分页参数来请求数据
      this.$request.get(`/apis/downResources/${this.pageNum}/${this.pageSize}`, {
        params: {
          search: name,
          typeId: 3
        }
      }).then(res => {
        this.searchLists = res.data?.list
        this.total = res.data?.total
        this.isLoading = false
        if (this.total === 0) {
          this.number = false
        }
      }).catch(error => {
        console.error('Failed to fetch data:', error);
        this.isLoading = false
      });
    },
    searchall() {
      this.number = true
      this.isLoading = true
      if (this.isActiveSet) {
        this.currentSearchValue = null
        this.$request.get(`/apis/downResources/${this.pageNum}/${this.pageSize}`, {
          params: {
            rootId: this.pid,
            typeId: 3
          }
        }).then(res => {
          this.searchLists = res.data?.list
          this.total = res.data?.total
          this.isLoading = false
          if (this.total === 0) {
            this.number = false
          }
        })
      } else {
        this.currentSearchValue = null
        this.$request.get(`/apis/downResources/${this.pageNum}/${this.pageSize}`, {
          params: {
            rootId: this.form.pid,
            typeId: 3
          }
        }).then(res => {
          this.searchLists = res.data?.list
          this.total = res.data?.total
          this.isLoading = false
          if (this.total === 0) {
            this.number = false
          }
        })
      }
    },
    //查询左边按钮数据
    load() {
      return this.$request.get('/apis/downCategories/list', {
        params: {
          type: 1,
          typeId: 3
        }
      }).then(res => {
        let sortedData = res.data.sort((a, b) => a.showOrder > b.showOrder ? 1 : -1);
        let activeIndex = -1;
        sortedData.forEach((item, index) => {
          if (item.name.toLowerCase() === this.form.categoryName.toLowerCase()) { // 忽略大小写比较
            activeIndex = index;
          }
        });
        this.buttonItems = sortedData;
        this.activeIndex = activeIndex;
        return sortedData;
      }).catch(error => {
        console.error('Error loading categories:', error);
        throw error;
      });
    },
    loadApps() {
      this.number = true
      return this.$request.get(`/apis/downCategories/list`, {
        params: {
          pid: this.form.pid,
          typeId: 3,
          type: 2
        }
      }).then(res => {
        this.apps = res.data
        if (this.apps.length === 0) {
          this.number = false
        }
        // let allApps = [];
        // res.data.forEach(category => {
        //   if (category.children && category.children.length > 0) {
        //     allApps = allApps.concat(category.children);
        //   }
        // });
        // this.apps = allApps;
      });
    },
    fetchData() {
      this.number = true
      this.currentSearchValue = this.form.name
      return this.$request.get(`/apis/downResources/${this.pageNum}/${this.pageSize}`, {
        params: {
          search: this.form.name,
          typeId: 3
        }
      }).then(res => {
        this.searchLists = res.data?.list;
        // 注意：这里你可能是想设置某个具体项的ID，而不是整个列表的ID
        // this.id = this.searchLists.id;  // 假设你想设置的是列表中的某个项的ID，需要修改逻辑
        this.total = res.data?.total;
        if (this.total === 0) {
          this.number = false
        }
      }).catch(error => {
        console.error('Failed to fetch data:', error);
      });
    },
    // 设置当前激活的按钮索引
    setActive(index, id) {
      this.number = true
      this.isLoading = true;
      this.pid = id;
      this.isActiveSet = true; // 设置标志位
      // this.remove();
      this.activeIndex = index === null ? null : index;
      this.form.categoryName = index === null ? '' : this.buttonItems[index].name; // 更新当前分类名称
      window.scrollTo(0, 0);

      if (this.activeIndex === null) {
        this.$router.push('/front/homeFront');
      } else {
        const fetchCategories = () => {
          if (this.activeIndex !== null) {
            return this.$request.get(`/apis/downCategories/list`, {
              params: {
                pid: id,
                typeId: 3,
                type: 2
              }
            }).then(res => {
              // let allApps = [];
              // res.data.forEach(category => {
              //   if (category.children && category.children.length > 0) {
              //     allApps = allApps.concat(category.children);
              //   }
              // });
              // this.apps = allApps;
              this.apps = res.data
              if (this.apps.length === 0) {
                this.number = false
              }
            });
          }
          return Promise.resolve();
        };

        this.currentSearchValue = null
        const fetchResources = () => {
          return this.$request.get(`/apis/downResources/${this.pageNum}/${this.pageSize}`, {
            params: {
              rootId: id,
              typeId: 3
            }
          }).then(res => {
            this.searchLists = res.data?.list;
            this.total = res.data?.total;
            if (this.total === 0) {
              this.number = false
            }
          });
        };

        Promise.all([fetchCategories(), fetchResources()]).then(() => {
          // 两个请求都完成后执行的代码
          this.isLoading = false;
        }).catch(error => {
          // 任何一个请求失败时执行的代码
          console.error('Error fetching data:', error);
          this.isLoading = false;
        });
      }
    },
    //每个软件的详情区域
    toDetail(id) {
      if (this.isActiveSet) {
        const item = this.buttonItems.find(item => item.id === this.pid);
        // 如果找到了，返回名称；如果没有找到，返回适当的提示
        const newCategoryName = item ? item.name : '未找到对应的名称';

        this.$router.push({
          name: 'DriveDetail',
          query: {
            id: id,
            newCategoryName: newCategoryName
          }
        });
      } else {
        const item = this.buttonItems.find(item => item.id === this.form.pid);
        // 如果找到了，返回名称；如果没有找到，返回适当的提示
        const newCategoryName = item ? item.name : '未找到对应的名称';

        this.$router.push({
          name: 'DriveDetail',
          query: {
            id: id,
            newCategoryName: newCategoryName
          }
        });
      }
    },
    handleCurrentChange(pageNum) {
      if (this.currentSearchValue === null) {
        this.pageNum = pageNum;
        this.searchall(); // 更新页码后重新请求数据
      } else {
        this.pageNum = pageNum;
        this.search(this.currentSearchValue); // 更新页码后重新请求数据
      }
    },
    handleSizeChange(pageSize) {
      if (this.currentSearchValue === null) {
        this.pageSize = pageSize;
        this.searchall(); // 更新每页条数后重新请求数据
      } else {
        this.pageSize = pageSize;
        this.search(this.currentSearchValue); // 更新每页条数后重新请求数据
      }
    },
  }
}
</script>

<style scoped>
.left-scroll-view-item {
  color: black; /* 默认颜色 */
  margin: 1px 0;
  text-align: center;
  font-size: 14px;
  border: none;
}

.left-scroll-view-item.is-active {
  background-color: #d4dff4;
  color: blue; /* 激活时的颜色 */
  font-size: 15px;
  border: none;
}

.indicator-line {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 4px;
  background-color: blue;
}

.image-button-container {
  position: relative; /* 设置为相对定位，以便子元素可以使用绝对定位 */
  padding-bottom: 20px; /* 如果需要，为按钮下方的空间添加内边距（可选） */
}

.image-button-container img {
  width: 100%;
  height: auto;
  display: block; /* 确保图片不会受到内联元素默认行为的影响 */
  /* 注意：移除了margin-top和margin-bottom，因为它们现在由容器控制 */
}

.scalable-container {
  /* 确保缩放时容器本身不会改变大小 */
  width: 100%;
  height: 100%;
  transform-origin: top left;
}

.breadcrumb-and-rank {
  display: flex;
  align-items: center;
  margin: 15px 8px
}

.img {
  width: 60px;
  height: 56px;
  margin-right: 20px;
}

.name {
  font-size: 17px;
  margin: 7px 0;
  font-weight: bold;
}

.time {
  font-size: 13px;
  margin: 7px 8px;
}

.card {
  border-top: 1px solid #e0e0e0;
  display: flex;
  flex-direction: row;
  padding: 20px;
  cursor: pointer;
}

.card1 {
  width: auto;
  border: 1px solid #e0e0e0;
  text-align: center;
  box-sizing: border-box;
  padding: 8px;
  height: 140px;
  cursor: pointer;
}

.image {
  width: 75px;
  height: 70px;
}

.item-name {
  margin: 7px 0;
  font-weight: bold;
}

.button-name {
  margin-left: 18px;
  border: none;
}

.main-content {
  max-width: 1200px; /* 设置最大宽度 */
  margin: 0 auto; /* 居中显示 */
}

.item-right {
  padding-right: 8px;
  margin-left: 20px
}

.app {
  margin-top: 10px;
  border: 1px solid #e0e0e0;
  background: white;
}

.item-left {
  display: flex;
  flex-direction: column;
  align-items: stretch;
  background-color: white;
  margin-top: 8px;
  position: sticky;
  top: 5em;
}

.item-right-behind {
  background: white;
  margin-top: 20px;
}

.download-button {
  width: 10%;
  height: 5%;
  margin: 30px 20px
}

.el-col-20 {
  width: 85.5%;
}

.introduction-ellipsis {
  margin: 6px 0;
  line-height: 1.8;
  font-size: 12px;
//width: 750px; //white-space: nowrap; //overflow: hidden; //text-overflow: ellipsis;
}

.empty {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center;
  height: 100vh;
}
</style>